import { Component, OnInit, ViewEncapsulation, Injector, NgZone, ViewChild } from '@angular/core';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import { LazyLoadEvent } from 'primeng/api';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/primeng';
import {
    EstimatedCostServiceProxy,
    EstimatedCostDto,
    EstimatedCategoryCostDto,
    ComboboxItemDto
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { TypeCostDetailModalComponent } from '../shared/type-cost-detail-modal.component';
import * as _ from 'lodash';
import * as moment from 'moment';
import { TimerHelper } from '@shared/helpers/TimerHelper';

@Component({
    templateUrl: './timer.component.html',
    styleUrls: ['./timer.component.less'],
    encapsulation: ViewEncapsulation.None,
    animations: [appModuleAnimation()]
})
export class RealtimeCostTimerComponent extends AppComponentBase implements OnInit {
    @ViewChild('dataTable') dataTable: Table;
    @ViewChild('paginator') paginator: Paginator;
    @ViewChild('typeCostDetailModal') typeCostDetailModal: TypeCostDetailModalComponent;

    selectedDate = new Date();

    filterText = '';

    workShop: number;
    workShopComboboxs = new Array<ComboboxItemDto>();

    constructor(injector: Injector, public _zone: NgZone, public _costService: EstimatedCostServiceProxy) {
        super(injector);
    }

    ngOnInit(): void {
        this.registerEvents();
        this.workShopComboboxs = this.getWorkshops();
    }

    registerEvents(): void {
        const self = this;

        function onMessageReceived(message: EstimatedCostDto) {
            if (
                !TimerHelper.IsInMonth(
                    self.selectedDate.getFullYear(),
                    self.selectedDate.getMonth() + 1,
                    moment(message.time)
                )
            ) {
                return;
            }

            if (self.workShop && self.workShop.toString() !== message.workshop) {
                return;
            }

            let cost = _.find(self.primengTableHelper.records, e => e.batchId === message.batchId);

            if (cost) {
                cost.amount += message.amount;
                let typeCost = _.find(cost.typeCosts, e => e.category === message.category);

                if (typeCost) {
                    typeCost.amount += message.amount;
                } else {
                    cost.typeCosts.push(
                        new EstimatedCategoryCostDto({ category: message.category, amount: message.amount })
                    );
                }
            }
        }

        abp.event.on('app.cost.messageReceived', message => {
            self._zone.run(() => {
                onMessageReceived(message.cost);
            });
        });
    }

    dateChange() {
        this.getMonthlyCosts();
    }

    workShopChange() {
        this.getMonthlyCosts();
    }

    getMonthlyCosts(event?: LazyLoadEvent) {
        if (this.primengTableHelper.shouldResetPaging(event)) {
            this.paginator.changePage(0);

            return;
        }

        this.primengTableHelper.showLoadingIndicator();

        this._costService
            .getMonthlyBatchIdEstimatedCosts(
                undefined,
                this.selectedDate.getFullYear(),
                this.selectedDate.getMonth() + 1,
                this.workShop ? this.workShop.toString() : undefined,
                this.filterText,
                this.primengTableHelper.getSorting(this.dataTable),
                this.primengTableHelper.getMaxResultCount(this.paginator, event),
                this.primengTableHelper.getSkipCount(this.paginator, event)
            )
            .pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator()))
            .subscribe(result => {
                this.primengTableHelper.totalRecordsCount = result.totalCount;
                this.primengTableHelper.records = result.items;
                this.primengTableHelper.hideLoadingIndicator();
            });
    }
}
